<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="searchType" style="width: 170px; margin-right: 2px;">
          <el-option value="recoveryCode" label="回收单号" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
        </el-select>
        <el-input v-model.trim="searchText" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item label="客户类型:" prop="csmTypeId">
        <el-select v-model="query.csmTypeId" clearable filterable placeholder="请选择">
          <el-option v-for="(item, index) in customerTypeMap" :key="index" :label="item.desc" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="气瓶条码:" prop="cylinderCode">
        <el-input v-model="query.cylinderCode" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="气瓶类型:" prop="gasCylinderTypeId">
        <el-select v-model="query.gasCylinderTypeId" filterable clearable placeholder="请选择" :filter-method="filterCylinderType" @clear="clearCylinderType" @focus="focusCylinderType">
          <el-option v-for="(item, index) in cylinderTypeMap" :key="index" :label="item.dictShortName + '-' + item.dictName" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否超检:" prop="isOverCheck">
        <el-select v-model="query.isOverCheck" filterable clearable placeholder="请选择">
          <el-option :value="1" label="是" />
          <el-option :value="2" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否报废:" prop="isScrap">
        <el-select v-model="query.isScrap" filterable clearable placeholder="请选择">
          <el-option :value="1" label="是" />
          <el-option :value="2" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="回收时间:" :table-form-merge="2" class="merge-item">
        <el-date-picker
          v-model="queryDate"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="回收站点:">
        <el-tree-select
          v-model="query.recoveryDeptOrgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="query.option" label="包含下级" />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="2" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="columns"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <!-- 客户详情抽屉 -->
    <CsmDetail
      ref="csmDetail"
      :parent-fetch-data="refresh"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
      :group-type-map="groupTypeMap"
    />
  </div>
</template>

<script>
  import dayjs from 'dayjs'
  import { queryCylinderDict, cylinderRecoveryList, cylinderRecoveryExport, queryExportDomain } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  import {
    queryMap
  } from '@/api'
  export default {
    name: 'cylinderRecovery', // 气瓶回收
    components: {
      CsmDetail
    },
    data() {
      return {
        exportDomain: '', // 导出域名
        searchType: 'csmCode',
        searchText: '',
        actionColWidth: 80,
        searchParams: {},
        query: {
          csmTypeId: '',
          cylinderCode: '',
          gasCylinderTypeId: '',
          isOverCheck: '',
          isScrap: '',
          recoveryDeptOrgSNNo: '',
          recoveryDeptId: '',
          option: false
        },
        queryDate: [],
        treeData: [],
        tableData: {
          total: 0,
          data: []
        },
        customerTypeMap: [], // 客户类型
        cylinderTypeMap: [], // 气瓶类型
        cylinderTypeMapCopy: [], // 气瓶类型 备份
        calcTypeList: [],
        paymenFilList: [],
        groupTypeMap: []
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      columns: function() {
        return [
          {
            type: 'index',
            fixed: 'left'
          },
          {
            prop: 'recoveryCode',
            width: 150,
            label: '回收单号'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 105,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'csmName',
            width: 160,
            label: '客户名称'
          },
          {
            prop: 'csmTypeId',
            label: '客户类型',
            width: 140,
            render: (h, { row }) => <span>{row.csmTypeId && formatColumnMap(this.customerTypeMap, 'value', row.csmTypeId, 'desc')}</span>
          },
          {
            prop: 'cylinderCode',
            width: 150,
            label: '气瓶条码'
          },
          {
            prop: 'gasCylinderTypeName',
            label: '气瓶类型',
            width: 150,
            render: (h, { row }) => (<span>{row.gasCylinderTypeSpec + '-' + row.gasCylinderTypeName}</span>)
          },
          {
            prop: 'gasCylinderYear',
            label: '气瓶年份'
          },
          {
            prop: 'isOverCheck',
            label: '是否超检',
            render: (h, { row }) => {
              const str = row.isOverCheck === 1 ? '是' : '否'
              return <span>{str}</span>
            }
          },
          {
            prop: 'unitPrice',
            label: '回收单价(元)',
            width: 120
          },
          {
            prop: 'totalAmount',
            label: '回收总额(元)',
            width: 120
          },
          {
            prop: 'isScrap',
            label: '是否报废',
            render: (h, { row }) => {
              const str = row.isScrap === 1 ? '是' : '否'
              return <span>{str}</span>
            }
          },
          {
            prop: 'remark',
            width: 200,
            label: '备注'
          },
          {
            prop: 'recoveryDeptName',
            label: '回收站点',
            width: 180
          },
          {
            prop: 'deliverymanName',
            label: '操作人'
          },
          {
            label: '操作时间',
            prop: 'recoveryDate',
            width: 180,
            render: (h, { row }) => (
            <span>
              {row.recoveryDate && dayjs(row.recoveryDate).format('YYYY-MM-DD HH:mm')}
            </span>
          )
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap(), this.getCylinderTypeMap(), this.getExportDomain()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 查询枚举 客户类型
      async queryOptionsMap() {
        mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
          .then((res) => {
            this.customerTypeMap = res.data
          })
      },
      // 查询枚举 气瓶类型
      async getCylinderTypeMap() {
        const { data } = await queryCylinderDict({ status: 1 })
        this.cylinderTypeMap = []
        if (!data) return
        this.cylinderTypeMap = data.map(it => ({ ...it, label: it.dictName, value: it.id }))
        this.cylinderTypeMapCopy = data.map(it => ({ ...it, label: it.dictName, value: it.id }))
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (query.gasCylinderTypeId) {
          const info = this.cylinderTypeMap.find(item => item.id === query.gasCylinderTypeId)
          query.gasCylinderTypeId = info ? info.cylinderTypeCode : ''
        }
        if (this.searchType) {
          query[this.searchType] = this.searchText ? this.searchText : ''
        }
        if (this.queryDate && this.queryDate.length > 0) {
          query.recoveryDate = this.queryDate[0]
          query.recoveryDateEnd = this.queryDate[1]
        }
        if (query.option) {
          query.recoveryDeptId = 0
        }
        if (!query.recoveryDeptOrgSNNo) {
          delete query.recoveryDeptId
        }
        delete query.option
        const res = await cylinderRecoveryList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 获取组织机构数据
      async getTreeData() {
        console.log(this.orgList, 'this.orgList==')
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        console.log(data, 'data---==')
        this.treeData = getTreeData(data)
      // this.query.orgSNNo = this.orgList && this.orgList[0].orgSNNo
      // this.query.orgId = this.orgList && this.orgList[0].orgId
      // this.selectTreeChange(this.orgList[0])
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.query.recoveryDeptOrgSNNo = value.orgSNNo
        this.query.recoveryDeptId = value.orgId
      // this.$nextTick(() => {
      //   this.$refs.lbTable.fetch({ currentPage: 1 })
      // })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.columns))
          // copyColumn.pop() 删除操作列
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          cylinderRecoveryExport({
            // paramInfo: _this._getQuery(_this.searchParams),
            paramInfo: _this.searchParams,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${_this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 过滤
      filterCylinderType(valueStr) {
        const dataList = [...this.cylinderTypeMapCopy]// 拷贝
        if (valueStr && valueStr.trim()) {
          // (it.dictShortName||it.dictName)&&
          this.cylinderTypeMap = dataList.filter(it => {
            if (it.dictShortName || it.dictName) {
              return it.dictShortName.indexOf(valueStr) !== -1 || it.dictName.indexOf(valueStr) !== -1
            }
          })
        } else {
          this.cylinderTypeMap = dataList
        }
      },
      clearCylinderType() {
        const dataList = [...this.cylinderTypeMapCopy]// 拷贝
        this.cylinderTypeMap = dataList
      },
      focusCylinderType() {
        const dataList = [...this.cylinderTypeMapCopy]// 拷贝
        this.cylinderTypeMap = dataList
      }

    }
  }
</script>

<style lang="scss" scoped></style>
